package com.tticar.invmanager.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.Enum.CodeType;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.entity.ChangeRepository;
import com.tticar.invmanager.entity.InRepositoryDetail;
import com.tticar.invmanager.entity.OutRepositoryDetail;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.mapper.ChangeRepositoryMapper;
import com.tticar.invmanager.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 调拨单 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-12-10
 */
@Service
public class ChangeRepositoryServiceImpl extends ServiceImpl<ChangeRepositoryMapper, ChangeRepository> implements IChangeRepositoryService {
    @Autowired
    private ICodeCounterService codeCounterService;
    @Autowired
    private IOutRepositoryDetailService outRepositoryDetailService;
    @Autowired
    private IInRepositoryDetailService inRepositoryDetailService;
    @Autowired
    private IRepositoryCountService repositoryCountService;

    @Override
    public Page selectPage(ChangeRepository changeRepository, MyPage<ChangeRepository> page) {
        Map map = new HashMap<>(4);
        map.put("code", changeRepository.getCode());
        List<Map> maps = this.baseMapper.queryChangeRepositoryList(page, map);
        return page.setRecords(maps);
    }

    @Override
    public void delete(Long id) {
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", id);
        ChangeRepository changeRepository = selectOne(wrapper);
        if (changeRepository.getStatus() == 1) {
            throw new MyServiceException("已审核，无法删除");
        }
        changeRepository.setStatus(-1);
        updateById(changeRepository);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertNew(String rows, Long fromWearhouseId, Long toWearhouseId, Date orderTime, String remark) {
        List<Map> rowsList = JSONArray.parseArray(rows, Map.class);
        if (rowsList == null || rowsList.size() < 1) {
            throw new MyServiceException("调拨存货信息不能为空");
        }
        String dbCode = codeCounterService.getOrderCode(CodeType.DB);

        for (int i = 0; i < rowsList.size(); i++) {
            //插入调拨单
            ChangeRepository changeRepository = new ChangeRepository();
            try {
                changeRepository.setSkuId(Integer.parseInt(rowsList.get(i).get("id").toString()));
            } catch (Exception e) {
                throw new MyServiceException("商品列表存在无效的商品信息，请选择完善，或删除该行");
            }

            changeRepository.setCount(Integer.parseInt(rowsList.get(i).get("count").toString()));
            changeRepository.setCode(dbCode);
            changeRepository.setFromWearhouseId(fromWearhouseId);
            changeRepository.setToWearhouseId(toWearhouseId);
            changeRepository.setOrderTime(orderTime);
            changeRepository.setUsername(MySecurityUtils.currentUser().getUsername());
            changeRepository.setRemark(remark);
            changeRepository.setStatus(0);
            insert(changeRepository);

        }
    }

    @Override
    @Transactional
    public void correctChangeOrder(String dbCode) {
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("code", dbCode);
        List<ChangeRepository> changeRepositories = selectList(wrapper);
        if (changeRepositories == null || changeRepositories.size() < 1) {
            throw new MyServiceException("调拨单不存在");
        }
        String ckCode = codeCounterService.getOrderCode(CodeType.CK);
        String rkCode = codeCounterService.getOrderCode(CodeType.RK);
        for (ChangeRepository changeEntity : changeRepositories) {
            if (changeEntity.getStatus() != 0) {
                throw new MyServiceException("该调拨单状态已改变，不是待审核状态，请刷新页面。");
            }
            changeEntity.setStatus(1);
            updateById(changeEntity);
            //调出仓库生成出库单，更新库存信息
            OutRepositoryDetail outRepository = new OutRepositoryDetail();
            outRepository.setOrderTime(changeEntity.getOrderTime());
            outRepository.setBuszId(changeEntity.getId());
            outRepository.setRemark("调拨出库");
            outRepository.setCode(ckCode);
            outRepository.setSkuId(Long.parseLong(changeEntity.getSkuId().toString()));
            outRepository.setCount(Integer.parseInt(changeEntity.getCount().toString()));
            outRepository.setWearhouseId(changeEntity.getFromWearhouseId());
            outRepository.setUsername(MySecurityUtils.currentUser().getUsername());
            outRepository.setType(5);
            outRepositoryDetailService.insert(outRepository);
            repositoryCountService.updateRepositoryCount(outRepository.getSkuId(), changeEntity.getFromWearhouseId(), outRepository.getCount() * -1);

            //调入仓库生成入库单，更新库存信息
            InRepositoryDetail inRepositoryDetail = new InRepositoryDetail();
            inRepositoryDetail.setOrderTime(changeEntity.getOrderTime());
            inRepositoryDetail.setBuszId(changeEntity.getId());
            inRepositoryDetail.setRemark("调拨入库");
            inRepositoryDetail.setCode(rkCode);
            inRepositoryDetail.setSkuId(Long.parseLong(changeEntity.getSkuId().toString()));
            inRepositoryDetail.setCount(Integer.parseInt(changeEntity.getCount().toString()));
            inRepositoryDetail.setWearhouseId(changeEntity.getToWearhouseId());
            inRepositoryDetail.setUsername(MySecurityUtils.currentUser().getUsername());
            inRepositoryDetail.setType(5);
            inRepositoryDetailService.insert(inRepositoryDetail);
            repositoryCountService.updateRepositoryCount(inRepositoryDetail.getSkuId(), changeEntity.getToWearhouseId(), inRepositoryDetail.getCount());
        }


    }


}
